#region Summary

// 
// Owner : JackieHan 
// 
// Solution : LearnSolution 
// 
// Project : JackieHan.NHiberante.SessionManage
// 
// File : NHibernateFactory.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : NHibernate 工厂
// 
// History : 
//			2010-09-28 12:12:42	    Create 
// 

#endregion

#region Using

using System;
using System.Collections.Generic;
using System.Data;
using NHibernate;
using NHibernate.AdoNet;
using NHibernate.ByteCode.Castle;
using NHibernate.Cache;
using NHibernate.Cfg;
using NHibernate.Cfg.Loquacious;
using NHibernate.Connection;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Exceptions;
using NHibernate.Hql.Ast.ANTLR;
using NHibernate.Linq.Functions;
using NHibernate.Transaction;
using NHibernate.Type;

#endregion

namespace JackieHan.NHiberante.SessionManage
{
    /// <summary> 
    /// NHibernate 工厂
    /// </summary>
    public class NHibernateFactory
    {
        private static object lockOjb = new object();
        private static Configuration cfg = null;
        private static ISessionFactory factory;
        private static ISessionStorage sessionStorage;

        static NHibernateFactory()
        {
            sessionStorage = SessionStorageFactory.GetSessionStorage();
        }

        public static Configuration Configuration
        {
            get
            {
                lock (lockOjb)
                {
                    if (cfg == null)
                    {
                        CreateConfiguration();
                    }
                    return cfg;
                }
            }
            set { cfg = value; }
        }

        private static void CreateConfiguration()
        {
            cfg.SessionFactoryName("lambda");   //配置助记名
            cfg.Cache(c =>//缓存配置
                          {
                              c.DefaultExpiration = 15; //超时时间
                              c.Provider<HashtableCacheProvider>(); //缓存提供程序
                              c.QueryCache<StandardQueryCache>();//缓存查询提供程序
                              c.RegionsPrefix = "learn";//缓存前缀
                              c.UseMinimalPuts = true;//设置缓存性能
                          });
            cfg.CollectionTypeFactory<DefaultCollectionTypeFactory>();//设置连接类型工厂
            cfg.DataBaseIntegration(db =>//数据库基本设置
                                        {
                                            db.AutoCommentSql = true;//自动注释生成的Sql,便于调试
                                            db.Batcher<SqlClientBatchingBatcherFactory>();//批量操作提供程序工厂
                                            db.BatchSize = 15;//批量更新设置
                                            db.ConnectionProvider<DriverConnectionProvider>();//连接提供程序
                                            db.ConnectionReleaseMode = ConnectionReleaseMode.AfterTransaction;//连接释放模式
                                            db.ConnectionStringName = "learn";//连接字符串名称
                                            db.Dialect<MsSql2005Dialect>();//数据库方言 
                                            db.Driver<SqlClientDriver>();//数据库驱动
                                            db.ExceptionConverter<SQLStateConverter>();
                                            db.HqlToSqlSubstitutions = "true 1,false 0,yes 'Y' no 'N'"; //Hql转化成Sql对照表
                                            db.IsolationLevel = IsolationLevel.ReadCommitted;//事务隔离级别
                                            db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;//Hbm2DDLKeyWords
                                            db.LogFormatedSql = true;//显示漂亮的Sql
                                            db.LogSqlInConsole = true;//输出所有的Sql到控制台
                                            db.MaximumDepthOfOuterJoinFetching = 13;//连接查询深度
                                            db.PrepareCommands = true;//用Prepare方式处理Sql
                                            db.SchemaAction = SchemaAutoAction.Update;//数据库Schema动作
                                            db.Timeout = 30;//超时时间
                                            db.TransactionFactory<AdoNetTransactionFactory>();//事务工厂
                                        });
            cfg.HqlQueryTranslator<ASTQueryTranslatorFactory>();//Hql翻译类工厂
            cfg.LinqToHqlGeneratorsRegistry<DefaultLinqToHqlGeneratorsRegistry>();//翻译Linq到Hql的类
            cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
            //cfg.Mappings(map =>
            //                 {
            //                     map.DefaultCatalog = "learnCatalog";
            //                     map.DefaultSchema = "learnSchema";
            //                 });
            cfg.Proxy(proxy =>//延迟加载配置
                          {
                              proxy.ProxyFactoryFactory<ProxyFactoryFactory>();
                              proxy.Validation = false;
                          });
        }

        internal static ISessionFactory SessionFactory
        {
            get
            {
                if (factory == null)
                {
                    lock (lockOjb)
                    {
                        factory = Configuration.BuildSessionFactory();
                    }
                }
                return factory;
            }
        }

        public static ISession CreateSession()
        {
            ISession session = sessionStorage.Get();
            if (session == null)
            {
                session = SessionFactory.OpenSession();
                sessionStorage.Set(session);
            }
            return session;
        }
    }
}